<template>
  <ContentWrap>
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="title">宽带套餐选购</h2>
      <p class="subtitle">为您提供优质的宽带服务，选择适合您的套餐</p>
    </div>
  </ContentWrap>

  <!-- 套餐列表 -->
  <ContentWrap>
    <el-row :gutter="20" v-loading="loading">
      <el-col 
        :xs="24" 
        :sm="12" 
        :md="8" 
        :lg="6" 
        v-for="item in list" 
        :key="item.id"
      >
        <el-card 
          class="package-card" 
          :shadow="'hover'"
        >
          <!-- 套餐内容 -->
          <div class="package-content">
            <h3 class="package-name">{{ item.packageName }}</h3>
            <div class="package-speed">
              <span class="speed-value">{{ item.speed }}</span>
              <span class="speed-unit">宽带</span>
            </div>
            
            <div class="package-price">
              <span class="currency">¥</span>
              <span class="amount">{{ item.price }}</span>
              <span class="period">/{{ item.validityPeriod }}个月</span>
            </div>

            <div class="package-features">
              <ul>
                <li>
                  <el-icon><Connection /></el-icon>
                  高速光纤接入
                </li>
                <li>
                  <el-icon><Timer /></el-icon>
                  {{ item.validityPeriod }}个月服务保障
                </li>
                <li>
                  <el-icon><Service /></el-icon>
                  7×24小时售后支持
                </li>
                <li>
                  <el-icon><Monitor /></el-icon>
                  免费提供光猫设备
                </li>
              </ul>
            </div>

            <div class="package-action">
              <el-button 
                type="primary" 
                class="buy-button"
                @click="handleChoosePackage(item)"
              >
                立即订购
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </ContentWrap>

  <!-- 确认订购弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    title="确认订购"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="套餐名称">
        <span>{{ selectedPackage?.packageName }}</span>
      </el-form-item>
      <el-form-item label="宽带速率">
        <span>{{ selectedPackage?.speed }}</span>
      </el-form-item>
      <el-form-item label="套餐价格">
        <template v-if="discount > 0">
          <span class="line-through text-gray-400">¥{{ selectedPackage?.price }}</span>
          <span class="ml-2 text-red-500">¥{{ (selectedPackage?.price! * (1 - discount / 100)).toFixed(2) }}</span>
          <span class="ml-2 text-green-500">
            ({{ pointsInfo?.vipLevel === 2 ? 'VIP' : 'SVIP' }}用户享受{{ discount }}%折扣)
          </span>
        </template>
        <template v-else>
          <span class="text-red-500">¥{{ selectedPackage?.price }}</span>
        </template>
      </el-form-item>
      <el-form-item label="收货地址" prop="addressId">
        <el-select
          v-model="formData.addressId"
          placeholder="请选择收货地址"
          class="!w-100%"
        >
          <el-option
            v-for="item in addressList"
            :key="item.id"
            :label="`${item.recipientName} ${item.recipientPhone} ${item.address}`"
            :value="item.id"
          >
            <div class="address-option">
              <div class="address-info">
                <span class="name">{{ item.recipientName }}</span>
                <span class="mobile">{{ item.recipientPhone }}</span>
              </div>
              <div class="address-detail">{{ item.address }}</div>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注信息" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入备注信息"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleConfirmOrder" :loading="submitLoading">
        确认订购
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { BroadbandApi } from '@/api/broadband'
import { AddressApi } from '@/api/address'
import { OrderApi } from '@/api/order'
import { PointsApi } from '@/api/points'
import type { BroadbandVO } from '@/api/broadband'
import type { AddressVO } from '@/api/address'
import type { PointsRespVO } from '@/api/points'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { ContentWrap } from '@/components/ContentWrap'
import { Connection, Timer, Service, Monitor } from '@element-plus/icons-vue'

defineOptions({ name: 'BroadbandChoose' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const router = useRouter()

const loading = ref(false)
const list = ref<BroadbandVO[]>([])
const dialogVisible = ref(false)
const submitLoading = ref(false)
const selectedPackage = ref<BroadbandVO>()
const addressList = ref<AddressVO[]>([])
const pointsInfo = ref<PointsRespVO>()
const discount = ref(0)

// 表单数据
const formRef = ref()
const formData = reactive({
  addressId: undefined,
  remark: ''
})

// 表单校验规则
const formRules = {
  addressId: [{ required: true, message: '请选择收货地址', trigger: 'change' }]
}

// 查询套餐列表
const getList = async () => {
  loading.value = true
  try {
    const data = await BroadbandApi.getBroadbandPage({
      pageNo: 1,
      pageSize: 100,
      status: 0
    })
    list.value = data.list
  } catch (error) {
    message.error(t('common.queryError'))
  } finally {
    loading.value = false
  }
}

// 查询收货地址列表
const getAddressList = async () => {
  try {
    const data = await AddressApi.getAddressPage({
      pageNo: 1,
      pageSize: 100
    })
    addressList.value = data.list
  } catch (error) {
    message.error(t('common.queryError'))
  }
}

// 获取折扣信息
const getDiscount = async () => {
  try {
    const data = await PointsApi.getByUserId()
    pointsInfo.value = data
    // 根据VIP等级设置折扣
    switch (data.vipLevel) {
      case 2:
        discount.value = 3
        break
      case 3:
        discount.value = 5
        break
      default:
        discount.value = 0
    }
  } catch (error) {
    message.error('获取折扣信息失败')
  }
}

// 选择套餐
const handleChoosePackage = (item: BroadbandVO) => {
  selectedPackage.value = item
  dialogVisible.value = true
  // 获取收货地址列表
  getAddressList()
  // 获取折扣信息
  getDiscount()
}

// 确认订购
const handleConfirmOrder = async () => {
  if (!formRef.value) return
  await formRef.value.validate()
  
  if (!selectedPackage.value?.id || !selectedPackage.value?.price) {
    message.error('套餐信息不完整')
    return
  }

  if (!formData.addressId) {
    message.error('请选择收货地址')
    return
  }
  
  submitLoading.value = true
  try {
    // 调用订单创建接口
    await OrderApi.createOrder({
      broadbandId: selectedPackage.value.id,
      addressId: formData.addressId as string,
      remark: formData.remark || '',
      totalPrice: selectedPackage.value.price,
      status: 1, // 订单状态
      payTime: '' // 支付时间为空
    })
    message.success('订单创建成功，请前往我的订单页面完成支付')
    dialogVisible.value = false
  } catch (error) {
    message.error(t('common.createError'))
  } finally {
    submitLoading.value = false
  }
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.page-header {
  text-align: center;
  margin-bottom: 20px;

  .title {
    font-size: 32px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin-bottom: 12px;
  }

  .subtitle {
    font-size: 16px;
    color: var(--el-text-color-secondary);
  }
}

.package-card {
  position: relative;
  margin-bottom: 24px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-5px);
  }

  .package-content {
    padding: 20px;
    text-align: center;

    .package-name {
      font-size: 24px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 16px;
    }

    .package-speed {
      margin-bottom: 20px;

      .speed-value {
        font-size: 28px;
        font-weight: 600;
        color: var(--el-color-primary);
      }

      .speed-unit {
        font-size: 16px;
        color: var(--el-text-color-secondary);
        margin-left: 4px;
      }
    }

    .package-price {
      margin-bottom: 24px;

      .currency {
        font-size: 20px;
        font-weight: 500;
        color: var(--el-color-danger);
        vertical-align: super;
      }

      .amount {
        font-size: 36px;
        font-weight: 700;
        color: var(--el-color-danger);
      }

      .period {
        font-size: 14px;
        color: var(--el-text-color-secondary);
        margin-left: 4px;
      }
    }

    .package-features {
      margin-bottom: 24px;
      text-align: left;

      ul {
        list-style: none;
        padding: 0;
        margin: 0;

        li {
          display: flex;
          align-items: center;
          margin-bottom: 12px;
          color: var(--el-text-color-regular);
          font-size: 14px;

          .el-icon {
            margin-right: 8px;
            color: var(--el-color-primary);
            font-size: 16px;
          }
        }
      }
    }

    .package-action {
      .buy-button {
        width: 80%;
        height: 40px;
        font-size: 16px;
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .page-header {
    .title {
      font-size: 24px;
    }

    .subtitle {
      font-size: 14px;
    }
  }

  .package-card {
    .package-content {
      .package-name {
        font-size: 20px;
      }

      .package-speed {
        .speed-value {
          font-size: 24px;
        }
      }

      .package-price {
        .amount {
          font-size: 32px;
        }
      }
    }
  }
}

.address-option {
  padding: 4px 0;
  
  .address-info {
    margin-bottom: 4px;
    
    .name {
      font-weight: 500;
      margin-right: 12px;
    }
    
    .mobile {
      color: var(--el-text-color-secondary);
    }
  }
  
  .address-detail {
    color: var(--el-text-color-regular);
    font-size: 13px;
  }
}
</style>
